<template>
  <sub-layout :key="routeKey" :routes="formatRoutes" :need-base-layout="false" :text="text">
    <slot></slot>
  </sub-layout>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import SubLayout from '@/layout/subLayout/index.vue'

import { useProjectStore } from '@/store/project'
import { useUserStore } from '@/store/user'

import { deepClone } from '@/utils'

const { uid } = useUserStore()
const { menu, getMenu: getProjectMenu } = useProjectStore()

const route = useRoute()
const router = useRouter()
const pid = route.query.pid
const text = route.query.pname

const formatRoutes = ref<any[]>([])
const routeKey = ref(0)

const getMenu = async () => {
  if (menu.length === 0) {
    await getProjectMenu({
      uid,
      pid,
    })
  }

  formatRoutes.value = setRoutes()
  routeKey.value = +new Date()
}

const setRoutes = () => {
  const { menu } = useProjectStore()
  const routes = menu && menu.filter((v: any) => v.path !== '/project/home')

  const _routes = deepClone(routes)
  const formatFn = (routes: any) => {
    routes.forEach((r: any) => {
      if (!r.children || r.children.length === 0) {
        r.path = `${r.path}?pid=${pid}&pname=${text}`
      } else {
        formatFn(r.children)
      }
    })
  }

  formatFn(_routes)

  console.log('rrrr', _routes)

  return _routes

  // const formatRoutes = routes.map((r: any) => {
  //   return {
  //     ...r,
  //     path: `${r.path}?pid=${pid}&pname=${text}`,
  //   }
  // })

  // return formatRoutes
}

const whiteList: string[] = []
if (!pid || !text) {
  if (!whiteList.includes(route.path)) {
    router.push('/project/home')
  }
} else {
  getMenu()
}
</script>
